<?php

namespace iBrand\Shop\Backend\Http\Controllers;

use iBrand\Shop\Core\Models\Clerk;
use Encore\Admin\Auth\Database\Administrator;
use iBrand\Shop\Core\Repositories\ClerkRepository;
use Illuminate\Http\Request;
use iBrand\Shop\Core\Repositories\ClerkShopRepository;
use iBrand\Shop\Backend\Repository\StoreRepository;
use Illuminate\Support\Facades\Log;
use Validator;
use DB;
use Encore\Admin\Facades\Admin as LaravelAdmin;
use Encore\Admin\Layout\Content;


class ClerkController extends Controller
{
    protected $clerkRepository;
    protected $storeRepository;
    protected $clerkShopRepository;
    protected $main;
    protected static $num;
    protected static $abnormal;

    function __construct(
        ClerkRepository $clerkRepository
        , StoreRepository $storeRepository
        , ClerkShopRepository $clerkShopRepository
    )
    {
        $this->clerkRepository = $clerkRepository;
        $this->storeRepository = $storeRepository;
        $this->clerkShopRepository = $clerkShopRepository;
    }


    /**
     * 所有导购列表
     * @return Content
     */
    public function lists()
    {
        $where = [];
        $status = intval(request('status')) !== 0 ? 1 : 0;

        $where['status'] = $status;

        $title = request('title');
        $shop_name = request('shop_name');

        if (request('value') != '') {
            $where["$title"] = ['like', '%' . request('value') . '%'];
        }

        $lists = $this->clerkRepository->getListClerks($where, $shop_name);

        return LaravelAdmin::content(function (Content $content) use ($lists) {

            $content->header('门店导购');

            $content->breadcrumb(
                ['text' => '门店管理', 'url' => 'shop/list/store', 'no-pjax' => 1],
                ['text' => '门店', 'url' => 'shop/list/store', 'no-pjax' => 1],
                ['text' => '门店导购', 'url' => '', 'no-pjax' => 1, 'left-menu-active' => '门店导购']

            );

            $content->body(view('shop-backend::clerk.lists', compact('lists')));
        });
    }

    /**
     * 当前门店导购列表
     * @return mixed
     */
    public function index()
    {
        $shop_id = session('shop_id');

        $where = [];
        $shop = $this->storeRepository->find($shop_id);
        $title = request('title');
        if (request('value') != '') {
            $where["$title"] = ['like', '%' . request('value') . '%'];
        }

        $status = intval(request('status')) !== 0 ? 1 : 0;

        $where['status'] = $status;
        $where['shop_id'] = $shop_id;

        $lists = $this->clerkRepository->getClerkList($where);

        $status_1 = $lists->count();

        $where['status'] = 0;
        $status_0 = $this->clerkRepository->getClerkList($where)->count();


        return LaravelAdmin::content(function (Content $content) use ($lists, $shop, $shop_id, $status_0, $status_1, $status) {

            $content->header('导购管理');

            if (session()->has('shop_name')) {

                $content->description(session('shop_name'));
            }

            $content->breadcrumb(
                ['text' => '门店管理', 'url' => 'shop/list/store', 'no-pjax' => 1],
                ['text' => '导购列表', 'url' => '', 'no-pjax' => 1, 'left-menu-active' => '导购列表']
            );

            $content->body(view('shop-backend::clerk.index', compact('lists', 'shop', 'shop_id', 'status_1', 'status_0', 'status')));
        });

    }


    public function toggleStatus()
    {

        $status = request('status');
        $id = request('aid');
        $user = Clerk::find($id);
        if ($user) {
            $user->status = $status;
            $user->save();
            return $this->ajaxJson(true, 200, '', []);
        }
        return $this->ajaxJson(false, 400, '操作失败', []);
    }


    public function create()
    {
        $shop_id = request('shop_id');

        $shop = $this->storeRepository->find($shop_id);

        $is_has_clerk_owner = $this->clerkRepository->findWhere(['shop_id' => $shop_id, 'is_clerk_owner' => 1, 'status' => 1])->count();

        return LaravelAdmin::content(function (Content $content) use ($shop_id, $shop, $is_has_clerk_owner) {

            $content->header('添加导购');

            if (session()->has('shop_name')) {

                $content->description(session('shop_name'));
            }

            $content->breadcrumb(
                ['text' => '门店管理', 'url' => 'shop/list/store', 'no-pjax' => 1],
                ['text' => '添加导购', 'url' => '', 'no-pjax' => 1, 'left-menu-active' => '导购列表']
            );

            $content->body(view('shop-backend::clerk.create', compact('shop_id', 'shop', 'is_has_clerk_owner')));
        });
    }


    public function edit($clerk_id)
    {
        $shop_id = session('shop_id');

        $clerk = $this->clerkRepository->find($clerk_id);
        $is_has_clerk_owner = $this->clerkRepository->findWhere(['shop_id' => $shop_id, 'is_clerk_owner' => 1, 'status' => 1])->count();

        $shop = $this->storeRepository->find($shop_id);

        return LaravelAdmin::content(function (Content $content) use ($clerk, $shop_id, $is_has_clerk_owner, $shop) {

            $content->header('编辑导购');

            if (session()->has('shop_name')) {

                $content->description(session('shop_name'));
            }

            $content->breadcrumb(
                ['text' => '门店管理', 'url' => 'shop/list/store', 'no-pjax' => 1],
                ['text' => '编辑导购', 'url' => '', 'no-pjax' => 1, 'left-menu-active' => '导购列表']
            );

            $content->body(view('shop-backend::clerk.edit', compact('clerk', 'shop_id', 'is_has_clerk_owner', 'shop')));
        });

    }


    public function update($clerk_id)
    {
        $input = request()->except(['_token', 'file']);
        //验证
        $rules = array(
            'name' => "unique:o2o_clerk,name,$clerk_id",
            'email' => "unique:o2o_clerk,email,$clerk_id|email",
            'clerk_no' => "unique:o2o_clerk,clerk_no,$clerk_id",
            'mobile' => "required|unique:o2o_clerk,mobile,$clerk_id",

        );
        $message = array(
            "required" => ":attribute 不能为空",
            "unique" => ":attribute 已经存在",
            "email" => ":attribute 格式不正确"
        );

        $attributes = array(
            "name" => "名称",
            "email" => "Email",
            "mobile" => "手机号码",
            "clerk_no" => '工号'
        );

        $validator = Validator::make(
            $input,
            $rules,
            $message,
            $attributes
        );
        if ($validator->fails()) {
            $warnings = $validator->messages();
            $warning = $warnings->first();
            return $this->ajaxJson(false, 400, '', $warning);
        }


        foreach ($input as $k => $item) {
            if ($item == '') {
                unset($input[$k]);
            }
        }
        try {
            DB::beginTransaction();

            if ($clerk = $this->clerkRepository->update($input, $clerk_id)) {
                event('on.shop.create.clerk', [$clerk]);
            }
            DB::commit();
            return $this->ajaxJson(true, 200, '', []);

        } catch (\Exception $exception) {
            DB::rollBack();
            \Log::info($exception->getMessage() . $exception->getTraceAsString());
            return $this->ajaxJson(false, 400, '数据异常', []);
        }
    }


    /**
     * 新增导购
     * @return \Illuminate\Http\JsonResponse
     */
    public function store()
    {
        $prefix = config('ibrand.app.database.prefix', 'ibrand_');

        $input = request()->except(['_token', 'file', 'password_confirmation']);
        //验证
        $rules = array(
            'email' => "unique:" . $prefix . "o2o_clerk,email|email",
            'clerk_no' => "unique:" . $prefix . "o2o_clerk,clerk_no",
            'mobile' => "required|unique:" . $prefix . "o2o_clerk,mobile"
        );
        $message = array(
            "required" => ":attribute 不能为空",
            "unique" => ":attribute 已经存在",
            "email" => ":attribute 格式不正确"
        );

        $attributes = array(
            "name" => "名称",
            "email" => "Email",
            "mobile" => "手机号码",
            "clerk_no" => '工号'
        );

        $validator = Validator::make(
            $input,
            $rules,
            $message,
            $attributes
        );
        if ($validator->fails()) {
            $warnings = $validator->messages();
            $warning = $warnings->first();
            return $this->ajaxJson(false, 400, '', $warning);
        }

        foreach ($input as $k => $item) {
            if ($item == '') {
                unset($input[$k]);
            }
        }

        if (Administrator::where('mobile', $input['mobile'])->first()) {
            return $this->ajaxJson(false, 400, '', '手机号码已经被使用');
        }

        try {

            DB::beginTransaction();

            $clerk = Clerk::create($input);

            event('on.shop.create.clerk', [$clerk]);

            DB::commit();

            return $this->ajaxJson(true, 200, '', $clerk);


        } catch (\Exception $exception) {
            DB::rollBack();
            \Log::info($exception->getMessage() . $exception->getTraceAsString());
            return $this->ajaxJson(false, 400, '数据异常', []);
        }
    }


    public function settings()
    {
        return LaravelAdmin::content(function (Content $content) {

            $content->header('O2O设置');

            $content->breadcrumb(
                ['text' => '门店管理', 'url' => 'shop/list/store', 'no-pjax' => 1],
                ['text' => '基础设置', 'url' => 'shop/store/system', 'no-pjax' => 1],
                ['text' => 'O2O设置', 'url' => '', 'no-pjax' => 1, 'left-menu-active' => 'O2O设置']

            );

            $content->body(view('shop-backend::clerk.settings'));
        });
    }

}
